import time
import os
import sys
import concurrent.futures
import warnings
import requests
import threading

sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from app.api.services.translators import TranslateClient
from app.api.schemas import Lang

# 禁用 SSL 证书验证警告
warnings.filterwarnings(
    "ignore", category=requests.packages.urllib3.exceptions.InsecureRequestWarning
)

# translator = TranslateFactory.get_translator("edge")
translator = TranslateClient.get_translator("baidu")


def translate_content(content):
    thread_name = threading.current_thread().name
    print(
        f"线程名称: {thread_name} 正在处理内容: {content[:30]}..."
    )  # 打印线程名称和内容的前 30 个字符
    return translator.translate(content, Lang.AUTO, Lang.EN, use_proxy=True)


def read_content_from_file(file_path):
    with open(file_path, "r", encoding="utf-8") as file:
        return file.readlines()


def write_content_to_file(file_path, content):
    with open(file_path, "w", encoding="utf-8") as file:
        file.write(content)


if __name__ == "__main__":
    input_file_path = r"D:\临时文件夹\translate_doc\1.txt"
    output_dir = r"D:\临时文件夹\translate_doc\out"
    os.makedirs(output_dir, exist_ok=True)
    content_list = read_content_from_file(input_file_path)

    start = time.time()
    # 使用 ThreadPoolExecutor 进行多线程翻译
    with concurrent.futures.ThreadPoolExecutor(max_workers=30) as executor:
        # 提交所有翻译任务
        futures = [
            executor.submit(translate_content, content.strip())
            for content in content_list
        ]

        # 获取所有翻译结果
        results = []
        for future in concurrent.futures.as_completed(futures):
            result = future.result()
            results.append(str(result))

    # 将翻译结果写入输出文件
    output_file_path = os.path.join(output_dir, os.path.basename(input_file_path))
    translated_content = "\n".join(results)
    write_content_to_file(output_file_path, translated_content)

    print(f"翻译结果已写入: {output_file_path}")

    print("------------------------------------\n")
    print("耗时：{:.2f} 秒".format(time.time() - start))
